package neuronvisualizer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileFilter;

public class DataFrame extends JFrame {
	private Driver parent;
	private JTextArea data;
	private JButton savefile;
	
	public DataFrame(Driver d){
		super("Data Output");
		parent = d;
		setupGUI();
		generateData();
		printData();
	}
	
	public void setupGUI(){
		this.setSize(400,400);
		this.setLayout(null);
		
		data = new JTextArea();
		data.setBounds(10,10,370,300);
		data.setEditable(false);
		add(data);
		
		savefile = new JButton("Save to File");
		savefile.setBounds(50,320,100,40);
		savefile.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent e){
						saveFile();
					}
				}
			);
		add(savefile);
		
		this.setVisible(true);
	}
	
	public void printData(){
		
	}
	
	public void saveFile(){
		JFileChooser fc = new JFileChooser();
		
		fc.setAcceptAllFileFilterUsed(false);
		
		fc.setFileFilter(new FileFilter(){
			public boolean accept(File f) {
		        if (f.isDirectory()) {
		            return true;
		        }
		        String filename = f.getName();
		        
		        if (filename != null) {
		            if (filename.endsWith(".txt")){
		                    return true;
		            } else {
		                return false;
		            }
		        }
		 
		        return false;
			}

			@Override
			public String getDescription() {
		        return "*.txt";
			}
				
		});

		int returnVal = fc.showSaveDialog(null);
		if(returnVal == JFileChooser.APPROVE_OPTION){
			File f = fc.getSelectedFile();
			if(!f.getName().endsWith(".txt")){
				f = new File(f.getAbsolutePath()+".txt");
			}
			try{
				FileWriter fstream = new FileWriter(f);
				BufferedWriter out = new BufferedWriter(fstream);
				for (String line : data.getText().split("\\n")){
					out.write(line);
					out.newLine();
				}
				
				out.close();				  
			}catch(Exception e){
				JOptionPane.showMessageDialog(null, "Error saving the file.");
			}
		}
	}
	
	public void generateData(){
		int totalNeurons;
		int neuronTally[]={0,0,0,0};
		
		int totalConnections = 0;
		int avgDegreeOfConnections = 0;
		
		totalNeurons = parent.getNeuronCount();
		for(int i=0;i<totalNeurons;i++){
			 Neuron n = parent.getNeuron(i);
			 neuronTally[n.getType().ordinal()]++;
			 totalConnections+=n.numberOfConnections();
			 
		}
		avgDegreeOfConnections = totalConnections/totalNeurons;
		
		data.append("Total Neurons: "+totalNeurons+"\n\r");
		data.append("Total Connections: "+totalConnections+"\n\r");
		data.append("Avg. Degree of Connections: "+avgDegreeOfConnections+"\n\r");
		data.append("\n\r");
		String[] Types = {"RS","LTS","IB","FS"};
		for(int i=0;i<Types.length;i++){
			data.append(""+Types[i]+" Neuron Count: "+neuronTally[i]+"\n\r");
		}
		
		HashMap<Long,ArrayList<Integer>> spikes = null;
		if(parent.getTimelineGUI()!=null){
			spikes = parent.getTimelineGUI().getTimeline().getSpikes();
		}
		if(spikes!=null){
			int totalSpikes=0;
			int spikesPerMS=0;
			for(Long i=(long)0;i<spikes.size();i++){
				try{
					totalSpikes += spikes.get((Long)i).size();
				}catch(Exception e){
					totalSpikes+=0;
				}
			}
			spikesPerMS = totalSpikes/spikes.size();
			data.append("\n\rTotal Neuron Spikes: "+totalSpikes+"\n\r");
			data.append("\n\rSpikes per milisecond: "+spikesPerMS);
		}
		
		for(int i=0;i<5;i++){
			for(int j=0;j<4;j++){
				
			}
		}
		
	}
}


